package com.hrzyit.base.ui.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View

/**
 * RecyclerViewAdapter基类
 * @author YangWei
 * @date 2019/3/10
 */
abstract class BaseRecyclerViewAdapter<T, VH : RecyclerView.ViewHolder>(var mContext: Context) : RecyclerView.Adapter<VH>() {

    // ItemClick 事件
    var mItemClickListener: OnItemClickListener<T>? = null

    // 数据集合
    var dataList: MutableList<T> = mutableListOf()

    /**
     * 绑定 View 持有人
     */
    override fun onBindViewHolder(holder: VH, position: Int) {

        holder.itemView.setOnClickListener {view ->
            if (mItemClickListener != null) {
                // 指定区域点击
                when(dataList.isNullOrEmpty()) {
                    true -> {
                        // 扩展：当没有数据时，返回一个 null 对象
                        mItemClickListener!!.onItemClick(view,null, position)
                    }
                    false -> {
                        mItemClickListener!!.onItemClick(view,dataList[position], position)
                    }
                }

            }
        }

    }

    /**
     * 数据记录数
     */
    override fun getItemCount(): Int {
        return dataList.size
    }

    /**
     * 设置数据
     * Presenter 处理过为 null 的情况，所以为不会为 Null
     */
    fun setData(sources: MutableList<T>) {
        dataList = sources
        notifyDataSetChanged()
    }


    /**
     * ItemClick事件声明
     */
    interface OnItemClickListener<in T> {
        fun onItemClick(view: View, item: T?, position: Int)

    }

    fun setOnItemClickListener(listener: OnItemClickListener<T>) {
        this.mItemClickListener = listener
    }
}